const { Service } = require("egg");
const Sequelize = require("sequelize");

class TopicQuestionBankService extends Service {
  async list({ lessonId, pageNum = 1, pageSize = 10 }) {
    const offset = (pageNum - 1) * pageSize;
    const questions = await this.app.model.TopicLessonQuestionBank.findAll({
      where: {
        lessonId,
      },
      order: [["updatedAt", "DESC"]],
      limit: pageSize,
      offset: offset,
      raw: true,
    });
    const total = await this.app.model.TopicLessonQuestionBank.count({
      where: {
        lessonId,
      },
      raw: true,
    });
    return {
      sorts: questions,
      total,
    };
  }

  async sortList(lessonId, num = 20) {
    const questions = await this.app.model.TopicLessonQuestionBank.findAll({
      where: {
        lessonId,
      },
      order: [[Sequelize.literal('RAND()')]],
      limit: num,
      raw: true,
    });
    return questions;
  }

  async create(data) {
    return await this.app.model.TopicLessonQuestionBank.create(data);
  }

  async createBulk(dataArray) {
    const results = await this.app.model.TopicLessonQuestionBank.bulkCreate(
      dataArray,
      {
        returning: true,
        validate: true,
      }
    );
    return results;
  }

  async delete(id) {
    return await this.app.model.TopicLessonQuestionBank.destroy({
      where: { id },
    });
  }

  async update(id, updateData) {
    const [updatedRows] = await this.app.model.TopicLessonQuestionBank.update(
      updateData,
      {
        where: { id },
      }
    );
    return updatedRows > 0 ? await this.findById(id) : null;
  }

  async findById(questionId) {
    return await this.app.model.TopicLessonQuestionBank.findByPk(questionId, {
      raw: true,
    });
  }
}

module.exports = TopicQuestionBankService;
